package com.zjdiepu.www.manage.api.base;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.filter.config.ConfigTools;
import com.alibaba.fastjson.JSON;
import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Add;
import com.zjdiepu.www.base.annotation.Id;
import com.zjdiepu.www.base.annotation.Update;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.CheckResult;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.common.consts.SystemConsts;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.common.util.UUIDFactory;
import com.zjdiepu.www.commpent.mapper.base.OtherAttachmentsVoMapper;
import com.zjdiepu.www.commpent.mapper.base.SysUserVoMapper;
import com.zjdiepu.www.config.AppProperty;
import com.zjdiepu.www.dao.system.BaseSalersmanMapper;
import com.zjdiepu.www.ibiz.base.IOtherAttachmentsService;
import com.zjdiepu.www.ibiz.base.ISysUserRoleService;
import com.zjdiepu.www.ibiz.base.ISysUserService;
import com.zjdiepu.www.model.base.dto.OtherAttachments;
import com.zjdiepu.www.model.base.dto.SysUser;
import com.zjdiepu.www.model.base.dto.SysUserRole;
import com.zjdiepu.www.model.base.ext.SysUserExt;
import com.zjdiepu.www.model.base.request.ChangePassword;
import com.zjdiepu.www.model.system.dto.BaseSalersman;
import com.zjdiepu.www.util.ExceptionHelper;
import com.zjdiepu.www.util.PasswordUtil;

/**
* 所属公司：稻普控股集团
* 项目名称：dpqc-parent-manager-home   
* 类名称：SysUserController   
* 类描述：   
* 创建人：zhangpp
* 创建时间：2017年4月7日 下午12:01:58   
* 修改人：zhangpp
* 修改时间：2017年4月7日 下午12:01:58   
* 修改备注：   
* @version V1.0
 */
@RestController
@RequestMapping(value = "user", produces="application/json;charset=UTF-8", method = RequestMethod.POST)
public class SysUserController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(SysUserController.class);
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ISysUserRoleService sysUserRoleService;
	@Autowired
	private IOtherAttachmentsService otherAttachmentsService;
	@Resource
	private OtherAttachmentsVoMapper otherAttachmentsVoMapper;
	@Resource
	private SysUserVoMapper sysUserVoMapper;
	@Resource
	private BaseSalersmanMapper baseSalersmanMapper;
	@Resource
	private AppProperty appProperty;
	
	@RequestMapping("login")
	public ApiResponse login(String loginName, String loginPass){
		
		if(StringUtils.isBlank(loginPass) || StringUtils.isBlank(loginPass)) {
			ExceptionHelper.thow(ResultFlagType.PARAM_EMPTY);
		}
		 //是否有此用户
        SysUser user = sysUserService.selectByName(loginName, false);
    	if (user == null) {
    		ExceptionHelper.thow("9999","账号不存在");
		}
    	//密码是否正确
    	String dbPasswordForMd5 = PasswordUtil.getDbPasswordForMd5(loginName, loginPass);
    	if(!dbPasswordForMd5.equals(user.getLoginPass())) {
    		ExceptionHelper.thow("9999","账号或密码错误");
    	}
    	//账号类型是否符合
//    	if(user.getAccountType() != null && 0 == user.getAccountType()) { //业务员不能登录管理系统
//    		ExceptionHelper.thow("9999", "业务员不能登录管理系统");
//    	}
    	//部门状态是否正确
    	if(DpStatus.INVALID.getCode().equals(user.getOrgDpStatus())){
    		ExceptionHelper.thow(ResultFlagType.DEPT_INVALID);
    	} else if(DpStatus.DELETED.getCode().equals(user.getOrgDpStatus())){
    		ExceptionHelper.thow(ResultFlagType.DEPT_DELETED);
    	}
    	
		try {
			List<String> codeUnits = user.getCodeUnits();
			String[] genKeyPair = ConfigTools.genKeyPair(1024);
			String priKey =  genKeyPair[0];  //私钥
			String pubKey = genKeyPair[1]; //公钥
			String codeUnitsJson = JSON.toJSONString(codeUnits);
			String encodeCodeUnits = ConfigTools.encrypt(priKey, codeUnitsJson);
			user.setEncodeCodeUnits(pubKey + "|" + encodeCodeUnits);
		} catch (Exception e) {
			logger.error("加密登录用户数据范围失败.", e);
		}
    	
    	HttpSession session = request.getSession(true);
    	session.setAttribute(CURRENT_USER_KEY, user);
    	return ApiResponse.success(true);
	}
	
	@RequestMapping(value="logout", method = {RequestMethod.POST,RequestMethod.GET})
	public ModelAndView logout(Model model){
		getCurrentUser(); //检查是否登录
		HttpSession session = request.getSession(true);
		session.removeAttribute(CURRENT_USER_KEY);
		session.invalidate();
		model.addAttribute("cssVersion", null);
		return new ModelAndView("redirect:/user/login");
	}
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: getList  <br/>
	 * @Description: 用户列表 <br/>
	 * @param userExt
	 * @return
	 * @version V1.0  <br/>
	 */
	@RequestMapping("getList")
	public ApiResponse getList(@ModelAttribute SysUserExt userExt) {
		getCurrentUser();
//		SysUser currentUser =(SysUser)getCurrentUser();
//		String currentUserId = currentUser.getId();
//		boolean admin = isSuper(currentUserId);
		/*if(!admin) {
			userExt.setCompanyId(currentUser.getCompanyId());
			userExt.setOrgId(currentUser.getOrgId());
		}*/
		userExt.notDeleted();
		PageVo page = getPage(userExt);
		int records = sysUserService.countByExt(userExt);
		page.setRecords(records);
		if(records > 0){
			List<SysUser> users = sysUserService.selectByExt(userExt);
			page.setRows(users);
		} else {
			page.setRows(CollectionInitUtil.emptyList());
		}
		return ApiResponse.success(page);
	}
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: getMuliList  <br/>
	 * @Description: 用户列表 <br/>
	 * @param userExt
	 * @return
	 * @version V1.0  <br/>
	 */
	@RequestMapping("getMuliList")
	public ApiResponse getMuliList(@ModelAttribute SysUserExt userExt, String roleIds) {
		getCurrentUser();
//		SysUser currentUser =(SysUser)getCurrentUser();
//		String currentUserId = currentUser.getId();
//		boolean admin = isSuper(currentUserId);
		/*if(!admin) {
			userExt.setCompanyId(currentUser.getCompanyId());
			userExt.setOrgId(currentUser.getOrgId());
		}*/
		if(StringUtils.isNotBlank(roleIds)) {
			String[] roleIds_ = roleIds.split(",");
			for(String roleId : roleIds_){
				if(StringUtils.isNotBlank(roleId)) {
					userExt.addRoleId(roleId.trim());
				}
			}
		}
		userExt.notDeleted();
		PageVo page = getPage(userExt);
		int records = sysUserService.countMuliByExt(userExt);
		page.setRecords(records);
		if(records > 0){
			List<SysUser> users = sysUserService.selectMuliByExt(userExt);
			sysUserVoMapper.mapper(users);
			page.setRows(users);
		} else {
			page.setRows(CollectionInitUtil.emptyList());
		}
		return ApiResponse.success(page);
	}

	/**
	 * @author xiongxiaotun <br/>
	 * @Title: queryOne  <br/>
	 * @Description: 用户详情 <br/>
	 * @param id
	 * @return
	 * @version V1.0  <br/>
	 */
	@RequestMapping("getById")
	public ApiResponse getById(String id) {
		if(StringUtils.isBlank(id)) {
			return ApiResponse.fail(ResultFlagType.PARAM_EMPTY.getCode(), "请选择用户");
		}
		SysUser user = sysUserService.selectById(id);
		if(null == user) {
			return ApiResponse.fail(ResultFlagType.MISSING.getCode(), "用户不存在");
		}
		String loanBank = user.getLoanBank();
		user.setLoanBankName(sysUserService.getBankNameFromBankCodes(loanBank));
		String headerImage = user.getHeaderImage();
		if(StringUtils.isNotBlank(headerImage)) {
			OtherAttachments headerImageRecord = otherAttachmentsService.selectById(headerImage);
			if(null != headerImageRecord) {
				otherAttachmentsVoMapper.mapper(headerImageRecord);
				if("01".equals(headerImageRecord.getFileHandleStatus())) {
					user.setHeaderImageSrc(headerImageRecord.getOssPath());
				} else {
					user.setHeaderImageSrc(headerImageRecord.getLocalFilePath());
				}
			}
		}
		String salersmanId = user.getSalersmanId();
		if(StringUtils.isNotBlank(salersmanId)) {
			BaseSalersman baseSalersman = baseSalersmanMapper.selectByPrimaryKey(salersmanId);
			if(null != baseSalersman) {
				user.setSalersmanName(baseSalersman.getName());
			}
		}
		
		return ApiResponse.success(user);
	}

	/**
	 * 添加用户
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param user
	 * @return
	 */
	@RequestMapping(value = { "add" }, method = { RequestMethod.POST })
	public ApiResponse add(@Validated(Add.class) SysUser user) {
		SysUser currentUser =(SysUser)getCurrentUser();
//		String currentUserId = currentUser.getId();
//		String currentCompanyId = currentUser.getCompanyId();
//		String targetCompanyId = user.getCompanyId();
//		if(StringUtils.isNotBlank(targetCompanyId) && !targetCompanyId.equals(currentCompanyId)) {
//			return ApiResponse.fail(CheckResult.TARGET_CAN_NOT_MOVE_TO_OTHER_COMPANY);
//		}
//		boolean admin = isSuper(currentUserId); //超级管理员
//		if(StringUtils.isNotBlank(targetCompanyId) && !targetCompanyId.equals(currentCompanyId) && !admin) {
//			return ApiResponse.fail(CheckResult.TARGET_CAN_NOT_MOVE_TO_OTHER_COMPANY);
//		}
//		if(!admin) {
//			user.setCompanyId(currentCompanyId);
//			user.setOrgId(currentUser.getOrgId());
//		}
		SysUser sysUser = new SysUser();
		sysUser.notDeleted();
		sysUser.setLoginName(user.getLoginName());
		boolean repeat = sysUserService.repeat(sysUser);
		if(repeat) {
			return ApiResponse.fail(ResultFlagType.REPEAT_DATA.getCode(), "用户登录名重复");
		}
		
		//5位随机密码，通过短信告知
//		String randomPassword = StringUtil.createRandomStr(5).toLowerCase();
		String randomPassword = SystemConsts.RESET_PASSWORD;
		
		user.setLoginPass(PasswordUtil.getDbPasswordForNormal(user.getLoginName(), randomPassword));
		user.setModifierName(currentUser.getName());
		user.setModifier(currentUser.getId());
		user.setCompanyId("1");
		sysUserService.saveUpdateAndDelete(true, user, currentUser, OperateType.add);
		
		/*
		 * 
		 * 发送短信等通知方式代码
		 * 
		 */
		return ApiResponse.success(true);
	}
	
	/**
	 * 修改用户
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param user
	 * @return
	 */
	@RequestMapping(value = { "modify" }, method = { RequestMethod.POST })
	public ApiResponse modify(@Validated(Update.class) SysUser user) {
		SysUser currentUser =(SysUser)getCurrentUser();
		String currentUserId = currentUser.getId();
		String currentCompanyId = currentUser.getCompanyId();
		boolean admin = isSuper(currentUserId);
		
		String targetCompanyId = user.getCompanyId();
		String targetUserId = user.getId();
		CheckResult checkUser = sysUserService.checkUser(currentCompanyId, currentUserId, admin, targetCompanyId, targetUserId);
		if(!CheckResult.TARGET_IS_NORMAL.equals(checkUser)) {
			return ApiResponse.fail(checkUser);
		}
//		if(!admin){
//			user.setCompanyId(currentCompanyId);
//			user.setOrgId(currentUser.getOrgId());
//		}
		SysUser sysUser = new SysUser();
		sysUser.notDeleted();
		sysUser.setId(user.getId());
		sysUser.setLoginName(user.getLoginName());
		boolean repeat = sysUserService.repeat(sysUser);
		if(repeat) {
			return ApiResponse.fail(ResultFlagType.REPEAT_DATA.getCode(), "用户登录名重复");
		}
		
		user.setLoginPass(null);
		user.setModifierName(currentUser.getName());
		user.setModifier(currentUserId);
		user.setCompanyId("1");
		sysUserService.saveUpdateAndDelete(true, user, currentUser, OperateType.edit);
		return ApiResponse.success(true);
	}

	/**
	 * 用户删除
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param userExt
	 * @return
	 */
	@RequestMapping("del")
	public ApiResponse del(@Validated(Id.class) SysUser user) {
		SysUser currentUser =(SysUser)getCurrentUser();
		String currentUserId = currentUser.getId();
		String currentCompanyId = currentUser.getCompanyId();
		boolean admin = isSuper(currentUserId);
		boolean success = false;
		CheckResult checkUser = null;
		for(String userId : user.getId().split(",")) {
			checkUser = sysUserService.checkUser(currentCompanyId, currentUserId, admin, null, userId);
			if(!CheckResult.TARGET_IS_NORMAL.equals(checkUser)) {
				continue;
			}
			
			SysUser user_ = new SysUser();
			user_.setId(userId);
			user_.setModifierName(currentUser.getName());
			user_.setModifier(currentUserId);
			success = true;
			sysUserService.saveUpdateAndDelete(true, user_, currentUser, OperateType.delete);
		}
		return success ? ApiResponse.success(true) : ApiResponse.fail(checkUser);
	}
	
	/**
	 * 用户禁用
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param userExt
	 * @return
	 */
	@RequestMapping("disable")
	public ApiResponse disable(@Validated(Id.class) SysUser user) {
		SysUser currentUser =(SysUser)getCurrentUser();
		String currentUserId = currentUser.getId();
		String currentCompanyId = currentUser.getCompanyId();
		boolean admin = isSuper(currentUserId);
		
		boolean success = false;
		CheckResult checkUser = null;
		for(String userId : user.getId().split(",")) {
			checkUser = sysUserService.checkUser(currentCompanyId, currentUserId, admin, null, userId);
			if(!CheckResult.TARGET_IS_NORMAL.equals(checkUser)) {
				continue;
			}
			SysUser user_ = new SysUser();
			user_.setId(userId);
			user_.setDpStatus(DpStatus.INVALID.getCode());
			user_.setModifierName(currentUser.getName());
			user_.setModifier(currentUser.getId());
			sysUserService.saveUpdateAndDelete(false, user_, currentUser, OperateType.edit);
			success = true;
		}
		return success ? ApiResponse.success(true) : ApiResponse.fail(checkUser);
	}
	
	/**
	 * 用户激活
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param userExt
	 * @return
	 */
	@RequestMapping("enable")
	public ApiResponse enable(@Validated(Id.class) SysUser user) {
		SysUser currentUser =(SysUser)getCurrentUser();
		String currentUserId = currentUser.getId();
		String currentCompanyId = currentUser.getCompanyId();
		boolean admin = isSuper(currentUserId);
		
		boolean success = false;
		CheckResult checkUser = null;
		for(String userId : user.getId().split(",")) {
			checkUser = sysUserService.checkUser(currentCompanyId, currentUserId, admin, null, userId);
			if(!CheckResult.TARGET_IS_NORMAL.equals(checkUser)) {
				continue;
			}
			SysUser user_ = new SysUser();
			user_.setId(userId);
			user_.setDpStatus(DpStatus.NORMAL.getCode());
			user_.setModifierName(currentUser.getName());
			user_.setModifier(currentUser.getId());
			sysUserService.saveUpdateAndDelete(false, user_, currentUser, OperateType.edit);
			success = true;
		}
		return success ? ApiResponse.success(true) : ApiResponse.fail(checkUser);
	}
	
	/**
	 * 重置密码
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param userExt
	 * @return
	 */
	@RequestMapping("reset")
	public ApiResponse reset(@Validated(Id.class) SysUser user) {
		SysUser currentUser =(SysUser)getCurrentUser();
		String currentUserId = currentUser.getId();
		String currentCompanyId = currentUser.getCompanyId();
		boolean admin = isSuper(currentUserId);
		
		boolean success = false;
		CheckResult checkUser = null;
		List<Map<String, String>> mobiles = new ArrayList<Map<String, String>>();
		for(String userId : user.getId().split(",")) {
			checkUser = sysUserService.checkUser(currentCompanyId, currentUserId, admin, null, userId);
			if(!CheckResult.TARGET_IS_NORMAL.equals(checkUser)) {
				continue;
			}
			
			SysUser user_ = new SysUser();
			user_.setId(userId);
			//5位随机密码，通过短信告知
//			String randomPassword = StringUtil.createRandomStr(5).toLowerCase();
			String randomPassword = SystemConsts.RESET_PASSWORD;
			//查询数据库用户信息
			SysUser dbUser = sysUserService.selectById(userId);
			if(null == dbUser) {
				return ApiResponse.fail(ResultFlagType.MISSING);
			}
			user_.setLoginPass(PasswordUtil.getDbPasswordForNormal(dbUser.getLoginName(), randomPassword));
			user_.setModifierName(currentUser.getName());
			user_.setModifier(currentUser.getId());
			sysUserService.saveUpdateAndDelete(false, user_, currentUser, OperateType.edit);
			success = true;
			
			Map<String, String> mobile = CollectionInitUtil.emptyMap();
			mobile.put("password", randomPassword);
			mobile.put("mobile", user_.getPhone());
			mobiles.add(mobile);
		}
		
		/*
		 *  批量短信通知代码
		 */
		return success ? ApiResponse.success(true) : ApiResponse.fail(checkUser);
	}
	
	/**
	 * 修改密码
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param userExt
	 * @return
	 */
	@RequestMapping("change")
	public ApiResponse reset(@Valid ChangePassword changePassword) {
		SysUser currentUser =(SysUser)getCurrentUser();
		if(!currentUser.getLoginPass().equals(changePassword.getOldPassword())){
			return ApiResponse.fail(ResultFlagType.OLD_PASSWORD_WRONG);
		}
		if(!changePassword.getEnsurePassword().equals(changePassword.getNewPassword())) {
			return ApiResponse.fail(ResultFlagType.ENSURE_PASSWORD_DIFFERENT);
		}
		currentUser.setLoginPass(PasswordUtil.getDbPasswordForMd5(currentUser.getLoginName(), changePassword.getNewPassword()));
		sysUserService.saveUpdateAndDelete(false, currentUser, currentUser, OperateType.edit);
		/**
		 * 清除状态，重新登录
		 */
		removeCurrentUser();
		return ApiResponse.success(true);
	}
	
	/**
	 * 用户授权
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param userExt
	 * @return
	 */
	@RequestMapping("grant")
	public ApiResponse grant(@Validated(Add.class) SysUserRole sysUserRole) {
		SysUser currentUser =(SysUser)getCurrentUser();
		String currentUserId = currentUser.getId();
		String currentCompanyId = currentUser.getCompanyId();
		boolean admin = isSuper(currentUserId);
		
		String userIds = sysUserRole.getUserId();
		boolean success = false;
		CheckResult checkUser = null;
		//添加当前角色
		List<SysUserRole> sysUserRoles = new ArrayList<SysUserRole>();
		for(String userId : userIds.split(",")){
			checkUser = sysUserService.checkUser(currentCompanyId, currentUserId, admin, null, userId);
			if(!CheckResult.TARGET_IS_NORMAL.equals(checkUser)) {
				continue;
			}
			
			String roleIds = sysUserRole.getRoleId();
			//删除老角色
			SysUserRole sysUserRoleDel_ = new SysUserRole();
			sysUserRoleDel_.setUserId(userId);
			sysUserRoleService.delete(sysUserRoleDel_);
			int now = (int)(System.currentTimeMillis() / 1000);
			for(String roleId : roleIds.split(",")) {
				if(StringUtils.isBlank(roleId)) {
					continue;
				}
				SysUserRole sysUserRole_ = new SysUserRole();
				sysUserRole_.setId(UUIDFactory.getUUID());
				sysUserRole_.setCreateTime(now);
				sysUserRole_.setUserId(userId);
				sysUserRole_.setRoleId(roleId);
				sysUserRoles.add(sysUserRole_);
				success = true;
			}
		}
		if(!success) {
			return ApiResponse.fail(checkUser);
		}
		sysUserRoleService.save(sysUserRoles);
		return ApiResponse.success(true);
	}
	
	@ApiOperation(value = "查询组织机构下面的业务员", httpMethod="POST", tags={"列表"})
    @RequestMapping("getByParentId")
    public ApiResponse getByParentId(@ModelAttribute  SysUserExt sysUserExt){
    	List<SysUser> dpBaseDataDictionaries = sysUserService.selectByExtServiceDep(sysUserExt);
        return ApiResponse.success(dpBaseDataDictionaries);
    }

}
